package com.ruoyi.durian.state.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.enums.DurianRedisKeysType;
import com.ruoyi.common.utils.RedisGeoUtils;
import com.ruoyi.common.utils.rabbitmq.RabbitSendUtils;
import com.ruoyi.durian.domain.LlOrder;
import com.ruoyi.durian.domain.utils.CalculateTheDistanceVoUtlis;
import com.ruoyi.durian.domain.vo.CalculateTheDistanceVo;
import com.ruoyi.durian.domain.vo.SendMessageReesultVo;
import com.ruoyi.durian.state.OrderState;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.LinkedHashMap;

/**
 * 司机到达乘客上车点状态实现
 */
@Component
public class EndOrderStateImpl implements OrderState {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RabbitSendUtils rabbitSendUtils;

    @Resource
    private RedisGeoUtils redisGeoUtils;

    @Override
    public void handleDriverArrival(SendMessageReesultVo messageDto, Point map) {

        String order = stringRedisTemplate.opsForValue().get(DurianRedisKeysType.ORDER.getKey() + messageDto.getReceiveId());
        LlOrder llOrder = JSONObject.parseObject(order, LlOrder.class);

        Long num = stringRedisTemplate.opsForValue().increment(DurianRedisKeysType.MIDWAY.getKey() + messageDto.getOrderId());

        LinkedHashMap<String, Point> linkMap = new LinkedHashMap<>();
        linkMap.put("midwayAddress:" + num, map);
        // 在指定订单地图中添加司机坐标
        redisGeoUtils.geoAdd(DurianRedisKeysType.GEO_ORDER.getKey() + messageDto.getOrderId(), linkMap);

        // 计算两点之间的距离以及何时到达
        // 计算司机到达起始点的距离
        Distance distance = redisGeoUtils.distance(DurianRedisKeysType.GEO_ORDER.getKey() + messageDto.getOrderId()
                , "midwayAddress:" + num, "finishAddress");
        // 计算两点之间的距离以及何时到达
        CalculateTheDistanceVo distanceVo = CalculateTheDistanceVoUtlis.calculateTheDistance(distance);
        messageDto.setAdvancedTime(distanceVo.getAdvancedTime());
        messageDto.setRang(distanceVo.getRang());

        if (messageDto.getRang().compareTo(new BigDecimal("0.05")) <= 0) {
            // 向乘客发送司机已到达的信息
            messageDto.setMessage("司机已到达指定下车地点！！！！");
        } else {
            messageDto.setMessage("司机预计" + messageDto.getAdvancedTime() + "到达行程终点，距离行程终点现在还有" + messageDto.getRang() + "KM");
        }
        // 向乘客发送司机预计到达的信息
        rabbitSendUtils.sendMessage(messageDto.getReceiveId(), JSONObject.toJSONString(messageDto));
    }
}
